<template>
  <div class="educoder-container">
    <!-- 导航栏 -->
    <NavBar :nav-items="navItems">
      <template #actions>
        <el-button v-if="isAdmin" type="primary" size="small" @click="router.push('/admin/settings')" class="admin-button">
          <el-icon class="mr-1"><Setting /></el-icon>
          管理员设置
        </el-button>
        <el-button v-if="!isAdmin" type="success" size="small" @click="router.push('/admin-login')" class="login-button">
          <el-icon class="mr-1"><User /></el-icon>
          管理员登录
        </el-button>
        <el-button v-if="isAuthorized || isAdmin" type="primary" size="small" @click="handleLogout">
          <el-icon class="mr-1"><SwitchButton /></el-icon>
          退出登录
        </el-button>
        <el-button v-else type="primary" size="small" @click="showAuthDialog">
          <el-icon class="mr-1"><Key /></el-icon>
          验证密码
        </el-button>
      </template>
      
      <template #mobile-actions>
        <el-button v-if="isAdmin" type="primary" @click="router.push('/admin/settings')" block class="admin-button mb-2">
          <el-icon class="mr-1"><Setting /></el-icon>
          管理员设置
        </el-button>
        <el-button v-if="!isAdmin" type="success" @click="router.push('/admin-login')" block class="login-button mb-2">
          <el-icon class="mr-1"><User /></el-icon>
          管理员登录
        </el-button>
        <el-button v-if="isAuthorized || isAdmin" type="primary" @click="handleLogout" block class="mb-2">
          <el-icon class="mr-1"><SwitchButton /></el-icon>
          退出登录
        </el-button>
        <el-button v-else type="primary" @click="showAuthDialog" block>
          <el-icon class="mr-1"><Key /></el-icon>
          验证密码
        </el-button>
      </template>
    </NavBar>
    
    <router-view @show-auth="showAuthDialog" />
    
    <!-- 赞赏按钮 - 仅在桌面端显示 -->
    <div class="donate-button desktop-only">
      <el-popover
        placement="left"
        :width="240"
        trigger="hover"
        popper-class="donate-popover"
      >
        <template #reference>
          <div class="donate-icon">
            <el-icon><List /></el-icon>
            <span>收录</span>
          </div>
        </template>
        
        <template #default>
          <div class="donate-container">
            <img 
              src="https://mybox-1257251314.cos.ap-chengdu.myqcloud.com/upload/myself/wechat.jpg" 
              alt="收录题库" 
              class="donate-image"
            />
          </div>
        </template>
      </el-popover>
    </div>
    
    <!-- 奶茶按钮 - 仅在桌面端显示 -->
    <div class="milk-tea-button desktop-only">
      <el-popover
        placement="left"
        :width="240"
        trigger="hover"
        popper-class="donate-popover"
      >
        <template #reference>
          <div class="milk-tea-icon">
            <el-icon><Coffee /></el-icon>
            <span>Coffee</span>
          </div>
        </template>
        
        <template #default>
          <div class="donate-container">
            <img 
              src="https://mybox-1257251314.cos.ap-chengdu.myqcloud.com/upload/myself/payforme.jpg" 
              alt="请我喝奶茶" 
              class="donate-image"
            />
          </div>
        </template>
      </el-popover>
    </div>
    
    <!-- 验证对话框 -->
    <el-dialog
      v-model="authDialogVisible"
      title="访客验证"
      :width="isMobile ? '95%' : '480px'"
      center
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      class="auth-dialog"
    >
      <div class="auth-dialog-content">
        <div class="auth-header">
          <h2 class="auth-title">2024-2025学年头歌题库</h2>
          <p class="auth-subtitle">访客验证 - 仅用于预览题库</p>
        </div>
        
        <PasswordInput 
          placeholder="请输入访客密码"
          buttonText="立即验证"
          @submit="handlePasswordSubmit"
        />
        
        <div class="auth-tips">
          <el-alert
            title="HTTPS://WWW.ROGINX.INK"
            type="info"
            :closable="false"
            show-icon
          />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper';
import { Coffee, List, SwitchButton, Key, Setting, User } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import { useMainStore } from './store';
import { usePermissionStore } from './store/permission';
import NavBar from './components/common/NavBar.vue';
import PasswordInput from './components/common/PasswordInput.vue';
import { validatePassword } from './utils/crypto';
import { initCosFileService } from './utils/dataService';
import cosConfig from './utils/cosConfig';

// 获取store实例和路由
const store = useMainStore();
const permissionStore = usePermissionStore();
const router = useRouter();
const route = useRoute();

// 导航菜单项
const navItems = [
  { title: '题库预览', path: '/preview', icon: 'Collection' },
  { title: '文件阅读器', path: '/file-reader', icon: 'Document' }
];

// 状态管理
const isAuthorized = computed(() => store.isPreviewAuthorized);
const isAdmin = computed(() => store.isAdmin);
const authDialogVisible = ref(false);

// 检测是否为移动设备
const isMobile = computed(() => window.innerWidth <= 768);

// 显示验证对话框
const showAuthDialog = () => {
  authDialogVisible.value = true;
};

// 处理密码提交
const handlePasswordSubmit = (password) => {
  if (validatePassword(password)) {
    store.setPreviewAuthorized(true, password);
    authDialogVisible.value = false;
    
    ElMessage({
      type: 'success',
      message: '密码验证成功，欢迎访问题库'
    });
  } else {
    ElMessage({
      type: 'error',
      message: '密码验证失败，请重试'
    });
  }
};

// 处理退出登录
const handleLogout = () => {
  ElMessageBox.confirm(
    '确定要退出登录吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 区分管理员和预览授权用户的退出逻辑
    if (store.isAdmin) {
      // 管理员退出
      store.clearAdmin();
      ElMessage({
        type: 'success',
        message: '已成功退出管理员账号'
      });
    } 
    
    if (store.isPreviewAuthorized) {
      // 预览授权用户退出
      store.setPreviewAuthorized(false);
      ElMessage({
        type: 'success',
        message: '已退出预览授权'
      });
    }
    
    router.push('/preview');
  }).catch(() => {
    // 取消退出
  });
};

// 监听路由变化，实现导航守卫
watch(() => route.path, (newPath) => {
  const targetRoute = router.resolve(newPath);
  
  // 检查路由是否需要授权
  if (targetRoute.meta.requiresAuth) {
    // 区分管理员权限和预览权限
    if (targetRoute.meta.requiresAdmin) {
      // 需要管理员权限的页面
      if (!store.isAdmin) {
        ElMessage.warning('该页面需要管理员权限，请先登录');
        router.push('/admin-login');
      }
    } else {
      // 普通需要授权的页面，预览授权或管理员都可访问
      if (!store.isPreviewAuthorized && !store.isAdmin) {
        ElMessage.warning('请先验证密码后再访问该页面');
        showAuthDialog();
      }
    }
  }
}, { immediate: true });

// 禁用复制粘贴函数
const disableCopyPaste = () => {
  const handleCopyPaste = (e) => {
    if (!permissionStore.canCopyPaste) {
      e.preventDefault();
      ElMessage({
        type: 'warning',
        message: permissionStore.copyPasteDisabledMessage
      });
      return false;
    }
  };
  
  // 监听复制粘贴相关事件
  document.addEventListener('copy', handleCopyPaste);
  document.addEventListener('cut', handleCopyPaste);
  document.addEventListener('paste', handleCopyPaste);
  
  return () => {
    // 清理事件监听
    document.removeEventListener('copy', handleCopyPaste);
    document.removeEventListener('cut', handleCopyPaste);
    document.removeEventListener('paste', handleCopyPaste);
  };
};

// 禁用右键菜单函数
const disableContextMenu = () => {
  const handleContextMenu = (e) => {
    if (!permissionStore.canUseContextMenu) {
      e.preventDefault();
      ElMessage({
        type: 'warning',
        message: permissionStore.contextMenuDisabledMessage
      });
      return false;
    }
  };
  
  // 监听右键菜单事件
  document.addEventListener('contextmenu', handleContextMenu);
  
  return () => {
    // 清理事件监听
    document.removeEventListener('contextmenu', handleContextMenu);
  };
};

// 组件挂载完成后的处理
onMounted(() => {
  // 初始化COS服务
  initCosFileService(cosConfig);
  
  // 应用权限控制
  const cleanupCopyPaste = disableCopyPaste();
  const cleanupContextMenu = disableContextMenu();
  
  // 组件卸载时清理事件监听
  onUnmounted(() => {
    cleanupCopyPaste();
    cleanupContextMenu();
  });
});
</script>

<style>
/* 全局样式重置 */
html, body {
  @apply m-0 p-0 w-full h-full font-sans antialiased bg-gray-50;
  overflow-x: hidden;
}

#app {
  @apply w-full h-full flex flex-col;
  overflow-x: hidden;
}

*, *::before, *::after {
  @apply box-border;
}

/* 移除默认边距 */
h1, h2, h3, h4, h5, h6, p, ul, ol {
  @apply m-0 p-0;
}

/* 链接样式 */
a {
  @apply text-blue-500 no-underline transition-colors duration-200;
}

a:hover {
  @apply text-orange-500;
}

/* 按钮样式 */
button {
  @apply cursor-pointer;
}

/* 图片样式 */
img {
  @apply max-w-full h-auto;
}

/* 隐藏滚动条但保持滚动功能 */
::-webkit-scrollbar {
  width: 0;
  height: 0;
  display: none;
}

/* Firefox滚动条样式 - 完全隐藏 */
* {
  scrollbar-width: none;
}

/* 确保所有滚动容器可以正常滚动 */
.el-scrollbar__wrap,
.el-table__body-wrapper,
.explorer-body,
.papers-grid-container,
[class*="-container"] {
  overflow-y: auto !important;
}

/* 赞赏按钮弹出层样式 */
.donate-popover {
  padding: 0 !important;
  border-radius: 8px !important;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15) !important;
  border: none !important;
}

/* 验证对话框样式 */
.auth-dialog .el-dialog {
  border-radius: 0.75rem;
  overflow: hidden;
  box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25) !important;
  margin-top: 15vh !important;
}

.auth-dialog .el-dialog__header {
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.05) 0%, rgba(249, 115, 22, 0.05) 100%);
  padding: 1rem;
  margin: 0;
  border-bottom: 1px solid #f3f4f6;
}

.auth-dialog .el-dialog__title {
  font-weight: 600;
  background: linear-gradient(135deg, #3b82f6, #f97316);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.auth-dialog .el-dialog__body {
  padding: 0;
}

.auth-dialog .el-dialog__headerbtn {
  top: 1rem;
  right: 1rem;
}

/* 全局弹出层样式修复 */
.el-popper.is-light {
  z-index: 2100 !important;
}

.el-overlay {
  z-index: 2000 !important;
}

/* 桌面端专用类 */
@media (max-width: 768px) {
  .desktop-only {
    display: none !important;
  }
  
  /* 修复移动端弹出层 */
  .el-popper {
    max-width: 90vw !important;
  }
  
  .el-dialog {
    width: 95% !important;
    max-width: 95% !important;
  }
  
  /* 修复移动端图片 */
  .donate-image {
    max-width: 100% !important;
    height: auto !important;
    max-height: 240px !important;
  }
  
  /* 修复移动端按钮 */
  .el-button {
    font-size: 14px !important;
  }
  
  /* 修复移动端图标 */
  .el-icon {
    font-size: inherit;
  }
  
  /* 修复移动端弹出层位置 */
  .el-popper.is-pure {
    position: fixed !important;
    left: 50% !important;
    transform: translateX(-50%) !important;
    top: 50% !important;
    margin-top: -120px !important;
  }
}
</style>

<style scoped>
body, html, #app{
  padding: 0 !important;
  margin: 0 !important;
}
.educoder-container {
  @apply w-full h-full flex flex-col;
}

/* 管理员按钮样式 */
.admin-button {
  background: linear-gradient(135deg, #10b981, #3b82f6);
  border: none;
  margin-right: 8px;
  transition: all 0.3s ease;
}

.admin-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
}

/* 登录按钮样式 */
.login-button {
  background: linear-gradient(135deg, #f59e0b, #10b981);
  border: none;
  margin-right: 8px;
  transition: all 0.3s ease;
}

.login-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(245, 158, 11, 0.3);
}

/* 赞赏按钮样式 */
.donate-button {
  position: fixed;
  right: 0;
  bottom: 40%;
  transform: translateY(-50%);
  z-index: 999;
}

.donate-icon {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 60px;
  height: 80px;
  background: linear-gradient(135deg, #3b82f6 0%, #f97316 100%);
  color: white;
  border-radius: 8px 0 0 8px;
  cursor: pointer;
  box-shadow: -2px 2px 10px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  padding: 10px 0;
}

.donate-icon:hover {
  width: 70px;
  background: linear-gradient(135deg, #2563eb 0%, #ea580c 100%);
}

.donate-icon .el-icon {
  font-size: 24px;
  margin-bottom: 5px;
}

.donate-icon span {
  font-size: 14px;
  letter-spacing: 2px;
}

.donate-container {
  transition: .3s;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.donate-image {
  width: 200px;
  height: 200px;
  object-fit: cover;
  border-radius: 8px;
  transition: transform 0.3s ease;
}

.donate-container:hover {
  border: #2563eb;
  transform: scale(1.4);
}

.donate-text {
  margin-top: 10px;
  font-size: 14px;
  color: #6b7280;
  text-align: center;
}

/* 奶茶按钮样式 */
.milk-tea-button {
  position: fixed;
  right: 0;
  bottom: 20%;
  transform: translateY(-50%);
  z-index: 999;
}

.milk-tea-icon {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 60px;
  height: 80px;
  background: linear-gradient(135deg, #ec4899 0%, #f97316 100%);
  color: white;
  border-radius: 8px 0 0 8px;
  cursor: pointer;
  box-shadow: -2px 2px 10px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  padding: 10px 0;
}

.milk-tea-icon:hover {
  width: 70px;
  background: linear-gradient(135deg, #db2777 0%, #ea580c 100%);
}

.milk-tea-icon .el-icon {
  font-size: 24px;
  margin-bottom: 5px;
}

.milk-tea-icon span {
  font-size: 14px;
  letter-spacing: 2px;
}

/* 验证对话框内容样式 */
.auth-dialog-content {
  padding: 2rem;
}

.auth-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 2rem;
}

.auth-title {
  font-size: 1.75rem;
  font-weight: 700;
  text-align: center;
  margin-bottom: 0.5rem;
  background: linear-gradient(135deg, #3b82f6, #f97316);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.auth-subtitle {
  font-size: 1.25rem;
  font-weight: 500;
  text-align: center;
  margin-bottom: 0.5rem;
  color: #6b7280;
}

.auth-tips {
  margin-top: 1.5rem;
}

@media (max-width: 768px) {
  .mb-2 {
    margin-bottom: 8px;
  }
  
  /* 移动端验证对话框样式调整 */
  .auth-dialog-content {
    padding: 1.5rem 1rem;
  }
  
  .auth-title {
    font-size: 1.5rem;
  }
  
  .auth-subtitle {
    font-size: 1rem;
  }
  
  /* 修复移动端按钮间距 */
  .mobile-actions .el-button + .el-button {
    margin-top: 8px;
  }
  
  /* 确保移动端图片不会超出容器 */
  .donate-container {
    max-width: 100%;
    overflow: hidden;
  }
  
  .donate-container:hover {
    transform: none;
  }
}
</style> 